package smsweb.servlet;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import smsweb.client.Util;
import smsweb.server.Sms;

public class SmsServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 197517650336290352L;
	
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		//resp.getWriter().println("Hello, world");
		PersistenceManager pm = Util.getPMF().getPersistenceManager();
		Sms message;
		/*long lng = System.currentTimeMillis();
		Sms message = new Sms("123456789", "Mesaj", new Date(), (long)lng);
		Key key = KeyFactory.createKey(Sms.class.getSimpleName(), lng);
		message.setKey(key);
		pm.makePersistent(message);
		*/
		Query query = pm.newQuery(Sms.class);
		query.setFilter("sent == false && incomingMessage == false" );
		query.setOrdering("date asc");
		try{
			List<Sms> results = (List<Sms>)query.execute();
			if(results != null && results.size() > 0) {
				message = results.get(0);
				resp.getWriter().println(message.toNetworkMessage());
			}
		}finally {
			query.closeAll();
		}
		pm.close();
        
	}
}
